import Router from '@koa/router';
import { getUploadUrl, getDownUrl } from '../common/oss.js';
import response from '../response.js';
import moment from 'moment';
import path from 'path';
import { WxService } from '../common/wx.js';
import { checkIdCard } from '../common/sm.js';
import db from '../mysqlHelper.js';
import fs from 'fs';
import PizZip from 'pizzip';

import sizeOf from 'image-size'; // 导入 image-size 模块
import { uploadFile ,downloadFile} from '../common/oss.js';
import {sendSms} from '../common/sms.js'


// 获取当前模块的目录名
const __dirname =process.cwd();
let authCode = [];
const router = new Router();
router.prefix('/api');
router.post(`/oss/getUploadUrl`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.filePath == null) {
        ctx.body = response.fail('缺少必填字段 文件路径');
        return;
    }
    let type = body.type || 'public';
    console.log(type);
    let url = await getUploadUrl(body.filePath, type);
    if (url instanceof Error) {
        ctx.body = response.fail(url.message);
        return;
    }
    ctx.body = response.success(url, '获取成功');

});
router.post(`/oss/getDownUrl`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.filePath == null) {
        ctx.body = response.fail('缺少必填字段 文件路径');
        return;
    }
    let url = await getDownUrl(body.filePath);
    if (url instanceof Error) {
        ctx.body = response.fail(url.message);
        return;
    }
    ctx.body = response.success(url, '获取成功');

});



router.post('/auth/sendSmsCode', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.phone == null) {
        ctx.body = response.fail('缺少必填字段 手机号');
        return;
    }
    let last = authCode.find(item => item.phone == body.phone);
    if (last && moment().diff(last.time, 'seconds') < 60) {
        ctx.body = response.fail('60秒内只能发送一次');
        return;
    }
    let code = Math.random().toString().slice(-6);
    let res = await sendSms(body.phone, code);
    if (res == false) {
        console.error(`手机号${body.phone}发送短信验证码失败`);
        ctx.body = response.fail('发送短信验证码失败');
        return;
    }
    console.log(`手机号${body.phone}验证码${code}成功`);
    authCode.push({ phone: body.phone, code, time: moment() })
    ctx.body = response.success({ code }, '发送成功');
});

router.post('/auth/checkSmsCode', async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }

    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 验证码');
        return;
    }
    let last = authCode.find(item => item.code == body.code);
    if (last == null) {
        ctx.body = response.fail('验证码不存在');
        return;
    }
    if (moment().diff(last.time, 'minutes') > 5) {
        ctx.body = response.fail('验证码已过期');
        return;
    }
    //移除验证过的验证码
    authCode = authCode.filter(item => item.code != body.code);
    //移除所有过期的验证码
    authCode = authCode.filter(item => moment().diff(item.time, 'minutes') < 5);
    ctx.body = response.success('验证成功');

});


//接收图片并上传到阿里云OSS
router.post('/upload/image', async (ctx) => {
    const file = ctx.request.files.file; // 获取上传文件
//获取上传文件的数组
    if (file == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if(ctx.request.body.ossPath == null){
        ctx.body = response.fail('缺少必填字段 ossPath');
        return;
    }
    let type ='public';
    if(ctx.request.body.type){
        type = ctx.request.body.type;
    }
    //获取流里的数组
    let buffer = fs.readFileSync(file.filepath);
    let result = await uploadFile(ctx.request.body.ossPath, buffer,type);
    if (result.code == 0) {
        ctx.body = response.fail(result.msg);
        return;
    }
    ctx.body = response.success(result, '上传成功');
});

router.post('/upload/file', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.filePath == null) {
        ctx.body = response.fail('缺少必填字段 文件路径');
        return;
    } 
    const file = ctx.request.files.file; // 获取上传文件
    if (file == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    //检查文件夹是否存在
    //检查上级文件夹是否存在
    console.log("__dirname", __dirname,body.filePath);
    const filename = path.join(__dirname, body.filePath);
  console.log("文件路径", filename);
    const parentDir = path.dirname(filename);
    console.log("文件夹", parentDir);
    if (!fs.existsSync(parentDir)) {
        fs.mkdirSync(parentDir, { recursive: true });
    }
    let reader
    let writer
    try {
        reader = fs.createReadStream(file.filepath);
        writer = fs.createWriteStream(filename);
        reader.pipe(writer);
    } catch
    {
        ctx.body = response.fail('上传失败');
        return;
    }
    ctx.body = response.success('上传成功');
}
);


router.post('/data/getSumData', async (ctx) => {
    let body = ctx.request.body;

    //获取一年的订单总数 支付状态为1的订单数和订单总金额
    let sql = `SELECT COUNT(*) as total,sum(price) as totalAmt FROM order_info WHERE YEAR(create_time) = YEAR(NOW()) and pay_status=1`;
    console.log(sql);
    let result = await db.query(sql);
    if (result.length == 0 ) {
        ctx.body = response.fail('获取订单总数失败');
        return;
    }
    if(result[0].total == null){
        result[0].total = 0;
    }
    if(result[0].totalAmt == null){
        result[0].totalAmt = 0;
    }
    let total = result[0].total;
    let totalAmt = result[0].totalAmt;
    sql =`SELECT sum(price) as cashTotal FROM order_info WHERE YEAR(create_time) = YEAR(NOW()) and pay_status=1 and pay_type=0`;
    result = await db.query(sql);
    if (result.length == 0 ) {
        ctx.body = response.fail('获取现金支付订单总数失败');
        return;
    }
    if(result[0].cashTotal == null){
        result[0].cashTotal = 0;
    }
    let cashTotal = result[0].cashTotal
    ctx.body = response.success({total,totalAmt,cashTotal},'获取成功');
});


export { router };

